//
//  SDHSportsNetRequest.m
//  SDHSportsNews
//
//  Created by MichaelShan on 2021/3/9.
//

#import "SDHSportsNetRequest.h"
#import "SDHSportsRequest.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"

@interface SDHSportsNetRequest () {
    NSInteger failNumber;
}

@end

@implementation SDHSportsNetRequest

static SDHSportsNetRequest *_sharedRequest = nil;
+ (instancetype)sharedRequest {
    @synchronized (self) {
        if (_sharedRequest == nil) {
            _sharedRequest = [[SDHSportsNetRequest alloc] init];
        }
    }
    
    return _sharedRequest;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    if (_sharedRequest == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedRequest = [super allocWithZone:zone];
        });
    }
    return _sharedRequest;
}

- (id)copyWithZone:(NSZone *)zone {
    return [SDHSportsNetRequest sharedRequest];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return [SDHSportsNetRequest sharedRequest];
}

- (id)init {
    if (self = [super init]) {
        _sharedRequest = [SDHSportsNetRequest sharedRequest];
        failNumber = 0;
    }
    
    return self;
}

- (BOOL)handleFailureBlock {
    BOOL networkState = [self netWorkReachabilityWithURLString:@"www.baidu.com"];
    if(!networkState){
        networkState = [self netWorkReachabilityWithURLString:@"www.google.com"];
    }
    if (!networkState && failNumber < 2) {
        failNumber ++;
        return NO;
    } else {
        failNumber = 0;
        return YES;
    }
}

- (BOOL)netWorkReachabilityWithURLString:(NSString *)strUrl {
    __block BOOL netState = NO;
    
    NSURL *baseURL = [NSURL URLWithString:strUrl];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    NSOperationQueue *operationQueue = manager.operationQueue;
    
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
            [operationQueue setSuspended:NO];
            netState = YES;
            break;
            case AFNetworkReachabilityStatusNotReachable:
            netState = NO;
            default:
            [operationQueue setSuspended:YES];
            break;
        }
    }];
    
    [manager.reachabilityManager startMonitoring];
    
    return netState;
}

#pragma mark - request
- (void)sendRequest:(SDHSportsRequest *)request returnValueBlock:(ReturnValueBlock)block
         errorBlock:(ErrorValueBlock)errBlock
       failureBlock:(FailureBlock)failureBlock {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 60;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    
    NSString *str = [[self dictionaryToUrlString:request.requestPara] stringByRemovingPercentEncoding];
    NSString *utf8Str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [[NSString alloc] initWithFormat:@"%@%@", request.requestUrl, utf8Str];
    
    NSLog(@"requestUrl: %@", url);
    NSURLSessionDataTask *task = [manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (block) {
            block(responseObject);
        }
        if ([responseObject[@"code"] intValue] != 200) {
            [MBProgressHUD showError:responseObject[@"msg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if ([self handleFailureBlock]) {
            if (failureBlock) {
                failureBlock();
            }
        } else {
            [MBProgressHUD showError:@"No network, please check your network state!"];
        }
    }];
    
    [task resume];
}

- (void)postRequest:(SDHSportsRequest *)request returnValueBlock:(ReturnValueBlock)block
  errorBlock:(ErrorValueBlock)errBlock
failureBlock:(FailureBlock)failureBlock {
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:request.requestUrl]];
    [urlRequest setHTTPMethod:@"post"];
    NSString *bodyString = [[self dictionaryToPostBody:request.requestPara] stringByRemovingPercentEncoding];
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    [urlRequest setHTTPBody:bodyData];
    [urlRequest setTimeoutInterval:30];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *responseObject = nil;
        if (data != nil) {
            responseObject = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        }
            
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                if (errBlock) {
                    errBlock(error);
                }
            } else if (block) {
                block(responseObject);
            }
        });
    }];
    
    [task resume];
}

/** 字典转http参数： */
- (NSString *)dictionaryToUrlString:(NSDictionary *)dic {
    if ([[dic allKeys] count] == 0) {
        return @"";
    }
    
    NSString *str = @"?";
    NSArray *key = [dic allKeys];
    NSArray *value = [dic allValues];
    
    for (int i = 0; i < [key count]; i++) {
        if ([key count] == (i + 1)) {
            str = [str stringByAppendingFormat:@"%@=%@", [key objectAtIndex:i], [value objectAtIndex:i]];
        } else {
            str = [str stringByAppendingFormat:@"%@=%@&", [key objectAtIndex:i], [value objectAtIndex:i]];
        }
    }
    
    return str;
}

- (NSString *)dictionaryToPostBody:(NSDictionary *)dic {
    if ([[dic allKeys] count] == 0) {
        return @"";
    }
    
    NSString *str = @"";
    NSArray *key = [dic allKeys];
    NSArray *value = [dic allValues];
    
    for (int i = 0; i < [key count]; i++) {
        if ([key count] == (i + 1)) {
            str = [str stringByAppendingFormat:@"%@=%@", [key objectAtIndex:i], [value objectAtIndex:i]];
        } else {
            str = [str stringByAppendingFormat:@"%@=%@&", [key objectAtIndex:i], [value objectAtIndex:i]];
        }
    }
    
    return str;
}

@end
